package com.xu.mb3.mbtools;

import org.apache.ibatis.io.Resources;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * Resources工具类用于读取resources文件
 *
 * @author xuguan
 * @since 2024/11/13
 */
public class ResourcesSample {

    public static void resourcesSample() {
        try {
            // 设置编码和默认类加载器
            Resources.setCharset(StandardCharsets.UTF_8);
            Resources.setDefaultClassLoader(ResourcesSample.class.getClassLoader());

            // 将文件读成流
            final InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            System.out.println(copyToString(is));

            // 将文件读成Reader
            final Reader reader = Resources.getResourceAsReader("mapper/UserAmountInfoMapper.xml");
            System.out.println(copyToString(reader));

            // 读取Properties文件
            final Properties properties = Resources.getResourceAsProperties("jdbc.properties");
            System.out.println(copyToString(properties));

            // 将url链接读成流
            final InputStream urlIs = Resources.getUrlAsStream("http://www.baidu.com");
            System.out.println(copyToString(urlIs));

            // 通过反射创建对象
            final Class<?> cls = Resources.classForName("com.xu.mybatis.entity.UserInfo");
            final Object obj = cls.newInstance();
            final Method setId = cls.getMethod("setId", Long.class);
            setId.invoke(obj, 10000L);
            System.out.println(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String copyToString(InputStream is) {
        try {
            final StringBuilder out = new StringBuilder();
            byte[] buffer = new byte[1024];
            int len;
            while (-1 != (len = is.read(buffer))) {
                out.append(new String(buffer, 0, len));
            }
            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String copyToString(Reader reader) {
        try {
            final StringBuilder out = new StringBuilder();
            char[] buffer = new char[1024];
            int len;
            while (-1 != (len = reader.read(buffer))) {
                out.append(new String(buffer, 0, len));
            }
            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String copyToString(Properties properties) {
        final StringBuilder out = new StringBuilder();
        properties.forEach((key, value) -> out.append(key).append("=").append(value).append("\n"));
        return out.toString();
    }

    public static void main(String[] args) {
        resourcesSample();
    }
}
